#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/27 15:50
# @Author  : Beam

import time,datetime
from subprocess import Popen,PIPE
import random
import psutil
import json

def cpu_count():
    return psutil.cpu_count()

def cpu_times():
    #CPU信息
    obj = psutil.cpu_times()
    result = {}
    result['user'] = obj.user  #表示用户空间程序的cpu使用率（没有通过nice调度）
    result['nice'] = obj.nice  #表示用户空间且通过nice调度过的程序的cpu使用率。
    result['system'] = obj.system  #表示系统空间的cpu使用率，主要是内核程序。
    result['idle'] = obj.idle   #空闲cpu
    result['iowait'] = obj.iowait  #cpu运行时在等待io的时间
    result['irq'] = obj.irq
    result['softirq'] = obj.softirq
    result['steal'] = obj.steal
    result['guest'] = obj.guest
    result['guest_nice'] = obj.guest_nice
    result['cpupercent'] = psutil.cpu_percent()
    return json.dumps(result,ensure_ascii=False)

def cpuload():
    result = {}
    result['nowpercent'] = psutil.cpu_percent()
    result['loadone'] = psutil.cpu_percent(1)  #1分钟负载
    result['loadfive'] = psutil.cpu_percent(5)  #5分钟负载
    result['loadfiften'] = psutil.cpu_percent(15)  #15分钟负载
    return json.dumps(result,ensure_ascii=False)



def sysparameters():
    result = {}
    result['usercount'] = len(psutil.users())
    result['cpuphysicalcount'] = psutil.cpu_count()   #cpu物理个数
    result['cpulogiccount'] = psutil.cpu_count(logical=False)  #cpu逻辑个数
    result['pids'] = len(psutil.pids())  #进程数
    #result['nowtime'] = str(datetime.datetime.fromtimestamp(psutil.boot_time())) #系统启动时间
    result['nowtime'] = float('%.2f' % (((time.time()+28800) - psutil.boot_time() )/60/60/24))  #系统运行时间（天）
    result['cpucurrent']= psutil.cpu_freq().current  #cpu当前频率
    result['memtotal'] = float(psutil.virtual_memory().total/1024/1024/1024)
    return json.dumps(result,ensure_ascii=False)

def memeryminions():
    #单位均为MB
    mem = psutil.virtual_memory()
    swapmem = psutil.swap_memory()
    result = {}
    result['total'] = mem.total/(1024 ** 2) #内存总数
    result['available'] = mem.available/(1024 ** 2)   #剩余内存
    result['percent'] = mem.percent   #已用百分比
    result['used'] = mem.used/(1024 ** 2)  #使用的内存
    result['free'] = mem.free/(1024 ** 2)  #未被使用的内存
    result['active'] = mem.active/(1024 ** 2)  #在使用或最近被使用的内存 RAM中
    result['inactive'] = mem.inactive/(1024 ** 2)  #未使用的内存
    result['buffers'] = mem.buffers/(1024 ** 2)   #缓存文件系统元数据等
    result['cached'] = mem.cached/(1024 ** 2)    #缓存各种东西
    result['shared'] = mem.shared/(1024 ** 2)    #被多个进程访问的内存
    result['swap_total'] = swapmem.total/(1024 ** 2)   #总交换内存
    result['swap_used'] = swapmem.used/(1024 ** 2)   #已使用的交换内存
    result['swap_free'] = swapmem.free/(1024 ** 2)    #可使用的交换内存
    result['swap_percent'] = swapmem.percent/(1024 ** 2)    #已用内存百分比
    result['swap_sin'] = swapmem.sin/(1024 ** 2)   #从磁盘交换的内存
    result['swap_sout'] = swapmem.sout/(1024 ** 2)   #从磁盘换出的内存
    return json.dumps(result,ensure_ascii=False)

def diskio():
    # IO变化
    ioobj = psutil.disk_io_counters()
    time.sleep(1)
    ioobj1 = psutil.disk_io_counters()
    result = {}
    #每项1秒的变化
    result['read_count'] = ioobj1.read_count - ioobj.read_count  #总读取次数
    result['write_count'] = ioobj1.write_count - ioobj.write_count #总写入次数
    result['read_bytes'] = ioobj1.read_bytes/1024 - ioobj.read_bytes/1024  #读取的总字节数（转换成M）
    result['write_bytes'] = ioobj1.write_bytes/1024 - ioobj.write_bytes/1024 #写入的总字节数（装换成M）
    result['read_time'] = ioobj1.read_time - ioobj.read_time   #从磁盘读取的时间（毫秒为单位）
    result['write_time'] = ioobj1.write_time - ioobj.write_time  #从磁盘写入的时间（毫秒为单位）
    #磁盘io变化
    result['all_read_count'] = ioobj1.read_count
    result['all_write_count'] = ioobj1.write_count
    result['all_read_bytes'] = ioobj1.read_bytes/1024
    result['all_write_bytes'] = ioobj1.write_bytes/1024
    result['all_read_time'] = ioobj1.read_time
    result['all_write_time'] = ioobj1.write_time
    return json.dumps(result,ensure_ascii=False)

def networkio():
    # 网络变化
    ioobj = psutil.net_io_counters()
    time.sleep(1)
    ioobj1 = psutil.net_io_counters()
    result = {}
    result['all_bytes_sent'] = ioobj1.bytes_sent  #发送的字节数
    result['all_bytes_recv'] = ioobj1.bytes_recv #收到的字节数
    result['all_packets_sent'] = ioobj1.packets_sent  #发送的数据包数量
    result['all_packets_recv'] = ioobj1.packets_recv  #接收的数据包数量
    result['all_errin'] = ioobj1.errin  #接收时错误的总数
    result['all_errout'] = ioobj1.errout  #发送时错误的总数
    result['all_dropin'] = ioobj1.dropin  #丢弃的数据包总数
    result['all_dropout'] = ioobj1.dropout   #丢弃的发送的包总数
    #每项1秒的变化
    result['bytes_sent'] = ioobj1.bytes_sent - ioobj.bytes_sent 
    result['bytes_recv'] = ioobj1.bytes_recv - ioobj.bytes_recv 
    result['packets_sent'] = ioobj1.packets_sent - ioobj.packets_sent  
    result['packets_recv'] = ioobj1.packets_recv - ioobj.packets_recv 
    result['errin'] = ioobj1.errin - ioobj.errin  
    result['errout'] = ioobj1.errout - ioobj.errout  
    result['dropin'] = ioobj1.dropin - ioobj.dropin  
    result['dropout'] = ioobj1.dropout - ioobj.dropout   

    return json.dumps(result,ensure_ascii=False)

def netstat():
    '''
    TCP连接数统计
    LISTEN:服务器在等待进入呼叫
    ESTABLISHED:正常数据传输状态
    TIME_WAIT:主动关闭
    CLOSE_WAIT:被动关闭
    LAST_ACK:等待所有分组死掉
    SYN_SENT:应用已经开始，打开一个连接
    '''
    status_list = ["LISTEN", "ESTABLISHED", "TIME_WAIT", "CLOSE_WAIT", "LAST_ACK", "SYN_SENT"]
    status_temp = []
    net_connections = psutil.net_connections()
    for key in net_connections:
        status_temp.append(key.status)
    result = {}
    for status in status_list:
        result[status] = status_temp.count(status)
    return json.dumps(result,ensure_ascii=False)


#print(sysparameters())
#print(memeryminions())
#print(diskio())
#print(networkio())
#print(netstat())

print(cpuload())
